package com.chuanye.mydrawable.activitys;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.chuanye.mydrawable.R;
import com.chuanye.mydrawable.adapters.AcceptuserAdapter;
import com.chuanye.mydrawable.adapters.FaultTypeAdapter;
import com.chuanye.mydrawable.adapters.LocaInfoAdapter;
import com.chuanye.mydrawable.adapters.RepairmanAdapter;
import com.chuanye.mydrawable.adapters.SpinnerOneAdapter;
import com.chuanye.mydrawable.beans.AcceptUserBean;
import com.chuanye.mydrawable.beans.AddRepairBean;
import com.chuanye.mydrawable.beans.City;
import com.chuanye.mydrawable.beans.DistrictrPersonBean;
import com.chuanye.mydrawable.beans.FaultTypeBean;
import com.chuanye.mydrawable.beans.LocaInfoBean;
import com.chuanye.mydrawable.beans.LoginBean;
import com.chuanye.mydrawable.json.LocalJson;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.chuanye.mydrawable.R.drawable.edittext_bg;

public class CreateRepairsActivity extends AppCompatActivity implements View.OnClickListener{
    private Context mContext;
    private List<City.CityBean> citylist = new ArrayList<>();//区县

    private List<DistrictrPersonBean.ListBean> listBeanlist = new ArrayList<>();//报修人
    private List<FaultTypeBean.ListBean> faulttypelist = new ArrayList<>();//故障类型

    private List<LocaInfoBean.ListBean> locainfolist = new ArrayList<>();//基站信息

    private List<AcceptUserBean.ListBean> acceptuserlist = new ArrayList<>();//受理人


    private TextView crre_region_tv; //区县
    private TextView crre_number_tv;//报修编号

    private EditText crre_repairman_tv;//报修人
    private EditText crre_phone_tv;//联系电话
    private EditText crre_repairunit_tv;//报修单位

    private TextView crre_faulttype_tv;//故障类型
    private TextView crre_stationname_tv;//站点名称
    private EditText crre_description_et;//站点描述
    private TextView crre_reportedman_tv;//接报人
    private TextView crre_receiverman_tv; //受理人
    private Button crre_submit_btn;

    private String Districtr = null;//全局 区县
    private String faulttypeId = null;//故障类型ID
    private String recipientid = null;//接报人ID
    private String RMuserID = null;//受理人ID
    private String LocaId = null;//站点ID

    private String faulttypename = null;//故障名称
    private ImageView crre_pulldown_iv;
    private FrameLayout crre_faulttype_fl;
    private FrameLayout crre_phone_fl;
    private FrameLayout crre_receiverman_fl;
    private FrameLayout crre_region_fl;
    private FrameLayout crre_repairunit_fl;
    private FrameLayout crre_stationname_fl;
    private LinearLayout crre_pulldown_ll;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_create_repairs);
        //初始化控件
        initView();

        initdata();

    }

    /**
     * 初始化控件
     */
    private void initView() {
        //区县
        crre_region_tv = (TextView) findViewById(R.id.crre_region_tv);
        crre_region_tv.setOnClickListener(this);
        //报修编号
        crre_number_tv = (TextView) findViewById(R.id.crre_number_tv);
        //报修人
        crre_repairman_tv = (EditText) findViewById(R.id.crre_repairman_tv);
        crre_pulldown_iv = (ImageView) findViewById(R.id.crre_pulldown_iv);//报修人下拉
        crre_pulldown_iv.setOnClickListener(this);
        //联系电话
        crre_phone_tv = (EditText) findViewById(R.id.crre_phone_tv);
        //报修单位
        crre_repairunit_tv = (EditText) findViewById(R.id.crre_repairunit_tv);
        //故障类型
        crre_faulttype_tv = (TextView) findViewById(R.id.crre_faulttype_tv);
        crre_faulttype_tv.setOnClickListener(this);
        //站点名称
        crre_stationname_tv = (TextView) findViewById(R.id.crre_stationname_tv);
        crre_stationname_tv.setOnClickListener(this);
        //站点描述
        crre_description_et = (EditText) findViewById(R.id.crre_description_et);
        //crre_description_et.setFocusable(false);
        //crre_description_et.setOnClickListener(this);
        //接报人
        crre_reportedman_tv = (TextView) findViewById(R.id.crre_reportedman_tv);
        //受理人
        crre_receiverman_tv = (TextView) findViewById(R.id.crre_receiverman_tv);
        crre_receiverman_tv.setOnClickListener(this);
        //提交
        crre_submit_btn = (Button) findViewById(R.id.crre_submit_btn);
        crre_submit_btn.setOnClickListener(this);

        //区县
        crre_region_fl = (FrameLayout) findViewById(R.id.crre_region_fl);
        //报修人
        crre_pulldown_ll = (LinearLayout) findViewById(R.id.crre_pulldown_ll);
        //联系电话
        crre_phone_fl = (FrameLayout) findViewById(R.id.crre_phone_fl);
        //报修单位
        crre_repairunit_fl = (FrameLayout) findViewById(R.id.crre_repairunit_fl);

        //故障类型
        crre_faulttype_fl = (FrameLayout) findViewById(R.id.crre_faulttype_fl);
        ///站点名称
        crre_stationname_fl = (FrameLayout) findViewById(R.id.crre_stationname_fl);
        //受理人
        crre_receiverman_fl = (FrameLayout) findViewById(R.id.crre_receiverman_fl);







    }

    private void initdata() {
        //区、县数据
        String str = LocalJson.city;
        Gson gson = new Gson();
        City city = gson.fromJson(str,City.class);
        citylist = city.getCity();

        //故障类型  http://172.16.1.121:9001/api/RepairProcess/GetAllFaultType
        String faulttype = LocalJson.GetAllFaultType;//获取站点类型信息
        Gson faulttypeGson = new Gson();
        FaultTypeBean faultTypeBean = gson.fromJson(faulttype,FaultTypeBean.class);
        faulttypelist = faultTypeBean.getList();

        //获取受理人数据
        getacceptuser(56);

        //获取用户登录信息
        SharedPreferences sharedPreferences = mContext.getSharedPreferences("User",MODE_PRIVATE);
        String strname = sharedPreferences.getString("name","");
        Gson gsonname = new Gson();
        LoginBean loginBean = gsonname.fromJson(strname,LoginBean.class);
        String username = loginBean.getObj().getAccountName();
        //接报人
        crre_reportedman_tv.setText(username);
        //接报人ID
        recipientid = String.valueOf(loginBean.getObj().getUserID());

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.crre_region_tv://区、县
                showPopupWindow(view);
                break;
            case R.id.crre_pulldown_iv://报修人
                if (listBeanlist == null || listBeanlist.size() <= 0){
                    Toast.makeText(mContext,"无报修人",Toast.LENGTH_SHORT).show();
                }else {
                    View view1 = (View) crre_pulldown_ll;
                    showRepairmanPopupWindow(view1);
                }

                break;
            case R.id.crre_faulttype_tv://故障类型
                showFaultTypePopupWindow(view);
                break;

            case R.id.crre_stationname_tv://站点名称
                if (locainfolist== null || locainfolist.size() <=0){
                    if (TextUtils.isEmpty(faulttypename)){
                        Toast.makeText(mContext,"请先选择故障类型",Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(mContext,"没有"+faulttypename,Toast.LENGTH_SHORT).show();
                    }

                }
                showLocaInfoPopupWindow(view);
                break;

            case R.id.crre_receiverman_tv://受理人
                showreceivermanPopupWindow(view);
                break;

            case R.id.crre_submit_btn://提交
                submit();
                break;
            case R.id.crre_description_et://描述
               // crre_description_et.setFocusable(true);
                break;

        }
    }

    /**
     * 提交
     */
    private void submit(){
        //区县
        String region = crre_region_tv.getText().toString().trim();
        if (TextUtils.isEmpty(region)){
            Toast.makeText(mContext,"区、县不能为空",Toast.LENGTH_SHORT).show();
            //crre_region_tv.setBackgroundResource(R.drawable.edittext_bg_red);
            return;
        }
        //报修编号
        String number = crre_number_tv.getText().toString().trim();
        if (TextUtils.isEmpty(number)){
            Toast.makeText(mContext,"报修编号不能为空",Toast.LENGTH_SHORT).show();
            return;
        }
        //报修人
        String repairman = crre_repairman_tv.getText().toString().trim();
        if (TextUtils.isEmpty(repairman)){
            Toast.makeText(mContext,"报修人不能为空",Toast.LENGTH_SHORT).show();
            return;
        }
        //联系电话
        String phone = crre_phone_tv.getText().toString().trim();
        if (TextUtils.isEmpty(phone)){
            Toast.makeText(mContext,"报修人不能为空",Toast.LENGTH_SHORT).show();
            return;
        }
        //报修单位
        String repairunit = crre_repairunit_tv.getText().toString().trim();
        if (TextUtils.isEmpty(repairunit)){
            Toast.makeText(mContext,"报修单位不能为空",Toast.LENGTH_SHORT).show();
            return;
        }

        //故障类型
        String faulttype = crre_faulttype_tv.getText().toString().trim();
        if (TextUtils.isEmpty(faulttype)){
            Toast.makeText(mContext,"故障类型不能为空",Toast.LENGTH_SHORT).show();
            return;
        }
        //站点名称
        String stationname = crre_stationname_tv.getText().toString().trim();
        if (TextUtils.isEmpty(stationname)){
            Toast.makeText(mContext,"站点名称不能为空",Toast.LENGTH_SHORT).show();
            return;
        }

        //站点描述
        String description = crre_description_et.getText().toString().trim();
        if (TextUtils.isEmpty(description)){
            Toast.makeText(mContext,"站点描述不能为空",Toast.LENGTH_SHORT).show();
            return;
        }
        //接报人
        String reportedman = crre_reportedman_tv.getText().toString().trim();
        if (TextUtils.isEmpty(reportedman)){
            Toast.makeText(mContext,"接报人不能为空",Toast.LENGTH_SHORT).show();
            return;
        }
        //受理人
        String receiverman = crre_receiverman_tv.getText().toString().trim();
        if (TextUtils.isEmpty(receiverman)){
            Toast.makeText(mContext,"受理人不能为空",Toast.LENGTH_SHORT).show();
            return;
        }
        AddOrUpdateRepair(number,repairman,phone
                ,repairunit,faulttypeId,description,recipientid,RMuserID,
                region,LocaId);

        /*{"RepairId":"20190122-京-CY-0012","RepairPersonnel":"猴哥","RepairTel":"0100000000000",
                "RepairCompany":"花果山","FaultType":"81B8C8B8-6673-4992-8E59-36334DCFE980",
                "Describe":"测试","RecipientID":2010,"RMuserID":17,"RecipientName":"董娜",
                "District":"朝阳区","LocaId":"73985329-c94c-4f1e-a8f3-673c670c8d18"}*/
    }

    /**
     *提交请求
     */
    private void AddOrUpdateRepair(String repairid,String repairpersonnel,String repairlel
    ,String repaircompany,String faulttype,String describe,String recipientid,String RMuserID,
                                   String District,String LocaId) {
        OkHttpUtils.post()
                .url("http://172.16.1.121:9001/api/RepairProcess/AddOrUpdateRepair")
                .addParams("RepairId", repairid)//报修编号
                .addParams("RepairPersonnel", repairpersonnel)//报修人
                .addParams("RepairTel", repairlel)//电话
                .addParams("RepairCompany", repaircompany)//报修单位
                .addParams("FaultType", faulttype)//故障类型 ID
                .addParams("Describe", describe)//描述
                .addParams("RecipientID", recipientid)//接报人  ID

                .addParams("RMuserID", RMuserID)//受理人 ID
                .addParams("District", District)//报修区县
                .addParams("LocaId", LocaId)//站点ID
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(okhttp3.Call call, Exception e, int id) {
                        Log.i("提交请求,请求异常：",e.toString());

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.i("提交请求：",response.toString());
                        Gson gson = new Gson();
                        String str = response.toString();
                        AddRepairBean addRepairBean = gson.fromJson(str,AddRepairBean.class);
                        if (addRepairBean.isSucceed()){
                            Toast.makeText(mContext,"提交成功",Toast.LENGTH_SHORT).show();

                            //区县
                            crre_region_fl.setBackgroundResource(R.drawable.etittext_bg_grey2);
                            crre_region_tv.setEnabled(false);//不可点击
                            crre_region_tv.setTextColor(R.color.textcolorgrey);
                            //报修编号
                            crre_number_tv.setTextColor(R.color.textcolorgrey);
                            //报修人
                            crre_pulldown_ll.setBackgroundResource(R.drawable.etittext_bg_grey2);
                            crre_repairman_tv.setEnabled(false);
                            crre_pulldown_iv.setClickable(false);
                            crre_repairman_tv.setTextColor(R.color.textcolorgrey);
                            //联系电话
                            crre_phone_fl.setBackgroundResource(R.drawable.etittext_bg_grey2);
                            crre_phone_tv.setEnabled(false);
                            crre_phone_tv.setTextColor(R.color.textcolorgrey);
                            //报修单位
                            crre_repairunit_fl.setBackgroundResource(R.drawable.etittext_bg_grey2);
                            crre_repairunit_tv.setEnabled(false);
                            crre_repairunit_tv.setTextColor(R.color.textcolorgrey);
                            //故障类型
                            crre_faulttype_fl.setBackgroundResource(R.drawable.etittext_bg_grey2);
                            crre_faulttype_tv.setEnabled(false);
                            crre_faulttype_tv.setTextColor(R.color.textcolorgrey);
                            ///站点名称
                            crre_stationname_fl.setBackgroundResource(R.drawable.etittext_bg_grey2);
                            crre_stationname_tv.setEnabled(false);
                            crre_stationname_tv.setTextColor(R.color.textcolorgrey);
                            //站点描述
                            crre_description_et.setBackgroundResource(R.drawable.etittext_bg_grey2);
                            crre_description_et.setEnabled(false);
                            crre_description_et.setTextColor(R.color.textcolorgrey);
                            //受理人
                            crre_receiverman_fl.setBackgroundResource(R.drawable.etittext_bg_grey2);
                            crre_receiverman_tv.setEnabled(false);
                            crre_receiverman_tv.setTextColor(R.color.textcolorgrey);
                            //提交
                            crre_submit_btn.setBackgroundResource(R.drawable.button_bg_nose);
                            crre_submit_btn.setClickable(false);
                            crre_submit_btn.setVisibility(View.GONE);

                        }else {
                            Toast.makeText(mContext,"提交失败",Toast.LENGTH_SHORT).show();
                        }




                    }
                });
    }


    /**
     * 弹出Popwindow  选择区县
     * @param view
     */
    private void showPopupWindow(View view) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.region_popwindow, null);
        //contentView.setBackgroundColor(Color.WHITE);
        contentView.setBackgroundResource(R.drawable.edittext_bg);
        // 设置按钮的点击事件
        ListView listview = (ListView) contentView.findViewById(R.id.region_pop_listview);
        SpinnerOneAdapter adapter = new SpinnerOneAdapter(mContext,citylist);

        //final PopupWindow popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        //final PopupWindow popupWindow = new PopupWindow(contentView, 500, 300, true);
        final PopupWindow popupWindow = new PopupWindow(contentView, crre_region_tv.getWidth(), 600, true);
        listview.setAdapter(adapter);
        popupWindow.setTouchable(true);

        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                Log.i("mengdd", "onTouch : ");

                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });

        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        //popupWindow.setBackgroundDrawable(getResources().getDrawable(Color.BLACK));
        popupWindow.setBackgroundDrawable(new ColorDrawable(0));
        // 设置好参数之后再show
        popupWindow.showAsDropDown(view);
        adapter.setSubClickListener(new SpinnerOneAdapter.SubClickListener() {
            @Override
            public void OntopicClickListener(View view, City.CityBean.CountyBean been, int position) {
                Log.i("选择区县：",been.getName()+" ,"+been.getNumber());
                crre_region_tv.setText(been.getName());
                Districtr = been.getName();
                //关闭popwindow
                popupWindow.dismiss();

                //获取区县下用户相关信息
                //清空集合
                if (listBeanlist != null && listBeanlist.size() > 0){
                    listBeanlist.clear();
                }
                //报修人
                crre_repairman_tv.setText("");
                //联系电话
                crre_phone_tv.setText("");
                //报修单位
                crre_repairunit_tv.setText("");
                //故障类型
                crre_faulttype_tv.setText("");
                //站点名称
                crre_stationname_tv.setText("");
                getAllDistrictrPerson(been.getName());
                //获取报修ID
                getRepairHandleExtend(been.getNumber());


            }
        });
    }

    /**
     * 弹出Popwindow  报修人
     * @param view
     */
    private void showRepairmanPopupWindow(View view) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.region_popwindow, null);
        //contentView.setBackgroundColor(Color.WHITE);
        contentView.setBackgroundResource(R.drawable.edittext_bg);
        // 设置按钮的点击事件
        final ListView listview = (ListView) contentView.findViewById(R.id.region_pop_listview);
        if (listBeanlist != null && listBeanlist.size() > 0){
            RepairmanAdapter adapter = new RepairmanAdapter(mContext,listBeanlist);
            listview.setAdapter(adapter);
            int n = 600;
            if (listBeanlist.size() < 6){
                n = dip2px(mContext,(40*listBeanlist.size()));
            }else {
                n = 600;
            }

            //final PopupWindow popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
            //final PopupWindow popupWindow = new PopupWindow(contentView, 500, 300, true);
            final PopupWindow popupWindow = new PopupWindow(contentView, view.getWidth(), n, true);

            popupWindow.setTouchable(true);

            popupWindow.setTouchInterceptor(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {

                    Log.i("mengdd", "onTouch : ");

                    return false;
                    // 这里如果返回true的话，touch事件将被拦截
                    // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
                }
            });

            // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
            // 我觉得这里是API的一个bug
            //popupWindow.setBackgroundDrawable(getResources().getDrawable(Color.BLACK));
            popupWindow.setBackgroundDrawable(new ColorDrawable(0));
            // 设置好参数之后再show
            popupWindow.showAsDropDown(view);

            listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    Log.i("报修人：",listBeanlist.get(i).getRepairPersonnel());
                    //报修人
                    crre_repairman_tv.setText(listBeanlist.get(i).getRepairPersonnel());
                    //联系电话
                    crre_phone_tv.setText(listBeanlist.get(i).getRepairTel());
                    //报修单位
                    crre_repairunit_tv.setText(listBeanlist.get(i).getRepairCompany());
                    popupWindow.dismiss();
                }
            });
        }




    }

    /**
     * 弹出Popwindow  故障类型
     * @param view
     */
    private void showFaultTypePopupWindow(View view) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.region_popwindow, null);
        //contentView.setBackgroundColor(Color.WHITE);
        contentView.setBackgroundResource(R.drawable.edittext_bg);
        // 设置按钮的点击事件
        ListView listview = (ListView) contentView.findViewById(R.id.region_pop_listview);
        FaultTypeAdapter adapter = new FaultTypeAdapter(mContext,faulttypelist);

        //final PopupWindow popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        //final PopupWindow popupWindow = new PopupWindow(contentView, 500, 300, true);
        final PopupWindow popupWindow = new PopupWindow(contentView, crre_region_tv.getWidth(), 600, true);
        listview.setAdapter(adapter);
        popupWindow.setTouchable(true);

        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                Log.i("mengdd", "onTouch : ");

                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });

        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        //popupWindow.setBackgroundDrawable(getResources().getDrawable(Color.BLACK));
        popupWindow.setBackgroundDrawable(new ColorDrawable(0));
        // 设置好参数之后再show
        popupWindow.showAsDropDown(view);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Log.i("故障类型：",faulttypelist.get(i).getName());
                //故障类型
                crre_faulttype_tv.setText(faulttypelist.get(i).getName());
                //故障类型ID
                faulttypeId = faulttypelist.get(i).getID();
                faulttypename = faulttypelist.get(i).getName();
                popupWindow.dismiss();

                //清空站点集合
                if (locainfolist != null && locainfolist.size() > 0){
                    locainfolist.clear();
                }
                crre_stationname_tv.setText("");
                //获取基站信息
                if (Districtr == null || Districtr.equals("")){
                    getLocaInfo("",faulttypelist.get(i).getID());
                }else {
                    getLocaInfo(Districtr,faulttypelist.get(i).getID());
                }



            }
        });
    }

    /**
     * 弹出Popwindow
     * @param view   站点名称选择
     */
    private void showLocaInfoPopupWindow(View view) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.region_popwindow, null);
        //contentView.setBackgroundColor(Color.WHITE);
        contentView.setBackgroundResource(R.drawable.edittext_bg);
        // 设置按钮的点击事件
        ListView listview = (ListView) contentView.findViewById(R.id.region_pop_listview);
        if (locainfolist != null && locainfolist.size() > 0) {
            LocaInfoAdapter adapter = new LocaInfoAdapter(mContext, locainfolist);
            listview.setAdapter(adapter);
            int n = 600;
            if (locainfolist.size() < 6) {
                n = dip2px(mContext, (40 * locainfolist.size()));
            } else {
                n = 600;
            }

            //final PopupWindow popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
            //final PopupWindow popupWindow = new PopupWindow(contentView, 500, 300, true);
            final PopupWindow popupWindow = new PopupWindow(contentView, crre_region_tv.getWidth(), n, true);

            popupWindow.setTouchable(true);

            popupWindow.setTouchInterceptor(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {

                    Log.i("mengdd", "onTouch : ");

                    return false;
                    // 这里如果返回true的话，touch事件将被拦截
                    // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
                }
            });

            // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
            // 我觉得这里是API的一个bug
            //popupWindow.setBackgroundDrawable(getResources().getDrawable(Color.BLACK));
            popupWindow.setBackgroundDrawable(new ColorDrawable(0));
            // 设置好参数之后再show
            popupWindow.showAsDropDown(view);
            listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    Log.i("点击了站点名称：", locainfolist.get(i).getLocaName());
                    //站点名称
                    crre_stationname_tv.setText(locainfolist.get(i).getLocaName());
                    //站点Id
                    LocaId = locainfolist.get(i).getLocaId();
                    popupWindow.dismiss();
                    //获取基站信息
                    //getLocaInfo(Districtr,faulttypelist.get(i).getID());


                }
            });
        }
    }

    /**
     * 弹出Popwindow
     * @param view   受理人选择
     */
    private void showreceivermanPopupWindow(View view) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.region_popwindow, null);
        //contentView.setBackgroundColor(Color.WHITE);
        contentView.setBackgroundResource(R.drawable.edittext_bg);
        // 设置按钮的点击事件
        ListView listview = (ListView) contentView.findViewById(R.id.region_pop_listview);
        if (acceptuserlist != null && acceptuserlist.size() > 0) {
            AcceptuserAdapter adapter = new AcceptuserAdapter(mContext, acceptuserlist);
            listview.setAdapter(adapter);
            int n = 600;
            if (acceptuserlist.size() < 6) {
                n = dip2px(mContext, (40 * acceptuserlist.size()));
            } else {
                n = 600;
            }

            //final PopupWindow popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
            //final PopupWindow popupWindow = new PopupWindow(contentView, 500, 300, true);
            final PopupWindow popupWindow = new PopupWindow(contentView, crre_region_tv.getWidth(), n, true);

            popupWindow.setTouchable(true);

            popupWindow.setTouchInterceptor(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {

                    Log.i("mengdd", "onTouch : ");

                    return false;
                    // 这里如果返回true的话，touch事件将被拦截
                    // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
                }
            });

            // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
            // 我觉得这里是API的一个bug
            //popupWindow.setBackgroundDrawable(getResources().getDrawable(Color.BLACK));
            popupWindow.setBackgroundDrawable(new ColorDrawable(0));
            // 设置好参数之后再show
            popupWindow.showAsDropDown(view);
            listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    Log.i("点击了受理人名称：", acceptuserlist.get(i).getUserName());
                    //受理人
                    crre_receiverman_tv.setText(acceptuserlist.get(i).getUserName());
                    //受理人ID
                    RMuserID = String.valueOf(acceptuserlist.get(i).getUserID());
                    popupWindow.dismiss();
                    //获取基站信息
                    //getLocaInfo(Districtr,faulttypelist.get(i).getID());


                }
            });
        }
    }

    /**
     *获取区县下用户相关信息
     */
    private void getAllDistrictrPerson(String county) {
        OkHttpUtils.post()
                .url("http://172.16.1.121:9001/api/RepairProcess/GetAllDistrictrPerson")
                .addParams("Districtr", county)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(okhttp3.Call call, Exception e, int id) {
                        Log.i("获取区县下用户相关信息,请求异常：",e.toString());

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.i("获取区县下用户相关信息：",response.toString());
                        Gson gson = new Gson();
                        String str = response.toString();
                        DistrictrPersonBean districtrpersonBean = gson.fromJson(str,DistrictrPersonBean.class);

                        if (districtrpersonBean.getList()!=null && districtrpersonBean.getList().size() > 0){
                            listBeanlist = districtrpersonBean.getList();
                        }else {
                            Toast.makeText(mContext,"无用户相关信息",Toast.LENGTH_SHORT).show();
                        }


                    }
                });
    }

    /**
     *根据 区县、基站类型 获取基站信息
     */
    private void getLocaInfo(String districtr,String faulttype) {
        OkHttpUtils.post()
                .url("http://172.16.1.121:9001/api/RepairProcess/GetLocaInfo")
                .addParams("Districtr", districtr)
                .addParams("FaultType", faulttype)
                .addParams("PageIndex", "0")
                .addParams("PageSize", String.valueOf(Integer.MAX_VALUE))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(okhttp3.Call call, Exception e, int id) {
                        Log.i("获取基站信息,请求异常：",e.toString());

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.i("获取基站信息：",response.toString());
                        Gson gson = new Gson();
                        String str = response.toString();
                        LocaInfoBean locaInfoBean = gson.fromJson(str,LocaInfoBean.class);

                        if (locaInfoBean.getList()!=null && locaInfoBean.getList().size() > 0){
                            locainfolist = locaInfoBean.getList();
                        }else {
                            Toast.makeText(mContext,"无基站数据",Toast.LENGTH_SHORT).show();
                        }


                    }
                });
    }

    /**
     *根据 Id 获取受理人
     */
    private void getacceptuser(int roleid) {
        OkHttpUtils.get()
                .url("http://172.16.1.121:9001/api/User")
                .addParams("RoleID", String.valueOf(roleid))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(okhttp3.Call call, Exception e, int id) {
                        Log.i("获取受理人,请求异常：",e.toString());

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.i("获取受理人：",response.toString());
                        Gson gson = new Gson();
                        String str = response.toString();
                        AcceptUserBean acceptUserBean = gson.fromJson(str,AcceptUserBean.class);

                        if (acceptUserBean.getList()!=null && acceptUserBean.getList().size() > 0){
                            acceptuserlist = acceptUserBean.getList();
                        }else {
                            Toast.makeText(mContext,"无受理人",Toast.LENGTH_SHORT).show();
                        }


                    }
                });
    }

    /**
     * 获取新的报修单ID
     * @param number
     */
    private void getRepairHandleExtend(String number) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date(System.currentTimeMillis());
        String str = format.format(date);
        Log.i("时间为：",str);
        String strr = str+"-"+number;
        OkHttpUtils.get()
                .url("http://172.16.1.121:9001/api/RepairHandleExtend")
                .addParams("request", strr)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(okhttp3.Call call, Exception e, int id) {
                        Log.i("获取新的报修单ID,请求异常：",e.toString());

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.i("获取新的报修单ID：",response.toString());
                        String str = response.toString();
                       String stt = str.substring(1,str.length()-1);
                        Log.i("获取新的报修单ID：",stt);
                        crre_number_tv.setText(stt);



                    }
                });
    }


    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result.append(temp);
            }
            return result.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    // 加密后解密
    public static String JM(String inStr) {
        char[] a = inStr.toCharArray();
        for (int i = 0; i < a.length; i++) {
            a[i] = (char) (a[i] ^ 't');
        }
        String k = new String(a);
        return k;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
}
